package com.dbtest;

import com.example.shujuku.pojo.Stu;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

public class Db {


    InputStream rs;
    SqlSessionFactory sq;
    SqlSession sqlSession;

    {
        try {
            rs = Resources.getResourceAsStream("mybatis-config.xml");
            /* sqlSession SqlSessionFactoryBuilder openSession打开会话 执行sql 语句*/
            sq = new SqlSessionFactoryBuilder().build(rs);
            /*openSession打开会话  执行sql*/
            sqlSession = sq.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Test
    public void DbTest(){
        Stu stu = sqlSession.selectOne("findById", "003");
        System.out.println(stu.getNumber());
        System.out.println(stu.getName());
        System.out.println(stu.getBirthday());
        System.out.println(stu.getStuclass());

        sqlSession.close();

    }

    @Test
    public void addStu() throws IOException{

        Stu stu = new Stu("007","小明",new Date(),"大数据1班");

        int row = sqlSession.insert("addStu", stu);

        sqlSession.commit();
        sqlSession.close();

        if (row>0){
            System.out.println("添加成功");
        }else {
            System.out.println("添加失败");
        }
    }

    @Test
    public void updateStu(){

            Stu stu = new Stu();
            stu.setName("上条当麻");
            stu.setBirthday(new Date());
            stu.setStuclass("某高中1班");

            stu.setNumber("007");

            int row =  sqlSession.update("updateStu", stu);

            sqlSession.commit();
            sqlSession.close();

            if (row>0){
                System.out.println("更改成功");
            }else {
                System.out.println("更改失败");
            }

    }

    @Test
    public void deleteStu() throws IOException{

        int row = sqlSession.delete("deleteStu", "007");

        sqlSession.commit();
        sqlSession.close();

        if (row>0){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }

    }

}
